import uuid
from common.config.enums import RedisInitKeyConfig
from fastapi import  Request
import jwt
from datetime import datetime, timedelta, timezone
from common.config.env import JwtConfig
from common.config.get_redis import RedisUtil

class CreateTokenService:
    # 生成token方法
    @classmethod
    async def create_jwt_access_token(cls,request: Request,data: dict, expires_delta:int,login_id:str):
        """
        根据登录信息创建当前用户token
        :param data: 登录信息
        :param expires_delta: token有效期
        :return: token
        """
        data["用户的令牌唯一标识"]=login_id
        to_encode = data.copy()
        expire = datetime.now(timezone.utc) + timedelta(minutes=expires_delta)
        to_encode.update({'exp': expire})
        session_id = str(uuid.uuid4())
        to_encode.update({'session_id': session_id})
        access_token = jwt.encode(to_encode, JwtConfig.jwt_secret_key, algorithm=JwtConfig.jwt_algorithm)
        # 此方法可实现同一账号同一时间只能登录一次
        await  RedisUtil.set_redis_value(request, f'{RedisInitKeyConfig.ACCESS_TOKEN.key}:{login_id}:{session_id}', access_token,
                                      timedelta(minutes=expires_delta))
        return access_token